<?php
/**
* @file newposts.php
* Systemblock Newposts
*
* @author PortaMx - Portal Management Extension
* @author Copyright 2008-2011 by PortaMx - http://portamx.com
* @Version: 1.0 RC4
* @Date: 23.02.2011
*/

if(!defined('PortaMx'))
	die('This file can\'t be run without PortaMx');

/**
* @class pmxc_newposts
* Systemblock Newposts
* @see newposts.php
* @author Copyright by PortaMx - http://portamx.com
*/
class pmxc_newposts extends PortaMxC_SystemBlock
{
	var $posts;				///< all posts
	var $topics;			///< all topics
	var $attaches;		///< all ataches
	var $isRead;			///< unread topics by member

	/**
	* InitContent.
	* Checks the cache status and create the content.
	*/
	function pmxc_InitContent()
	{
		global $context, $scripturl, $user_info, $pmxCacheFunc;

		// if visible init the content
		if($this->visible)
		{
			if($this->cfg['cache'] > 0)
			{
				// check the block cache
				if(($cachedata = $pmxCacheFunc['get']($this->cache_key, $this->cache_mode)) !== null)
				{
					list($this->topics, $isRead, $this->posts, $this->attaches) = $cachedata;
					$this->isRead = (isset($isRead[$user_info['id']]) ? $isRead[$user_info['id']] : null);
					if($this->isRead === null)
					{
						$cachedata = $this->fetch_data($isRead);
						$pmxCacheFunc['put']($this->cache_key, $cachedata, $this->cache_time, $this->cache_mode);
					}
				}
				else
				{
					$cachedata = $this->fetch_data();
					$pmxCacheFunc['put']($this->cache_key, $cachedata, $this->cache_time, $this->cache_mode);
				}
				unset($cachedata);
			}
			else
				$this->fetch_data();

			// paging...
			if(!empty($this->cfg['config']['settings']['onpage']) && count($this->posts) > $this->cfg['config']['settings']['onpage'])
				$this->pmxc_constructPageIndex(count($this->posts), $this->cfg['config']['settings']['onpage']);
		}
		// return the visibility flag (true/false)
		return $this->visible;
	}

	/**
	* fetch_data.
	* Fetch Messages and Attaches.
	*/
	function fetch_data($isRead = null)
	{
		global $context, $scripturl, $smcFunc, $settings, $modSettings, $user_info;

		$this->posts = null;
		$this->attaches = null;
		$this->topics = null;
		$this->isRead = null;
		$curRead = $this->get_isRead();

		if(isset($this->cfg['config']['settings']['boards']) && !empty($this->cfg['config']['settings']['boards']))
		{
			$ssiposts = ssi_recentTopics($this->cfg['config']['settings']['total'], null, $this->cfg['config']['settings']['boards'], '');

			if(!empty($ssiposts))
			{
				$msgids = array();
				foreach($ssiposts as $post)
				{
					preg_match('~msg(\d+)~', $post['href'], $found);
					$msgids[] = $found[1];
					$this->posts[$found[1]] = $post;
					$this->topics[] = $post['topic'];
					$this->isRead[$post['topic']] = $curRead['topic'] != $post['topic'] && !empty($post['is_new']) ? false : true;
				}
				unset($ssiposts);

				// get full messagebody
				$msg = array();
				$request = $smcFunc['db_query']('', '
					SELECT id_msg, body, smileys_enabled
						FROM {db_prefix}messages
					WHERE id_msg IN ({array_int:msgids})',
					array(
						'msgids' => $msgids
					)
				);

				while($row = $smcFunc['db_fetch_assoc']($request))
				{
					$msg = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
					censorText($msg);
					$this->posts[$row['id_msg']]['body'] = $msg;
				}
				$smcFunc['db_free_result']($request);

				// get attachments if show thumnails set
				if(AllowedTo('view_attachments', $this->cfg['config']['settings']['boards']))
				{
					if(!empty($this->cfg['config']['settings']['thumbs']))
					{
						$request = $smcFunc['db_query']('', '
							SELECT id_attach, id_thumb, filename, id_msg
								FROM {db_prefix}attachments
							WHERE id_msg IN ({array_int:msgids})
								AND approved = 1
								AND mime_type LIKE {string:like}
							ORDER BY id_attach',
							array(
								'msgids' => $msgids,
								'like' => 'IMAGE%'
							)
						);

						$thumbs = array();
						while($row = $smcFunc['db_fetch_assoc']($request))
						{
							if(!in_array($row['id_attach'], $thumbs))
							{
								$thumbs[] = $row['id_thumb'];
								$this->attaches[$row['id_msg']][] = array(
									'topic' => $row['id_msg'],
									'image' => $row['id_attach'],
									'thumb' => empty($row['id_thumb']) ? $row['id_attach'] : $row['id_thumb'],
									'fname' => str_replace('_thumb', '', $row['filename'])
								);
							}
						}
						$smcFunc['db_free_result']($request);
					}
				}

				$isRead[$user_info['id']] = $this->isRead;
				return array($this->topics, $isRead, $this->posts, $this->attaches);
			}
		}
	}

	/**
	* ShowContent.
	* Output the content and add necessary javascript
	*/
	function pmxc_ShowContent()
	{
		global $context, $settings, $modSettings, $scripturl, $txt;

		if(!is_null($this->posts))
		{
			$L_R = empty($context['right_to_left']) ? 'left' : 'right';
			$R_L = empty($context['right_to_left']) ? 'right' : 'left';

			// put the rescale code to the content
			if(!empty($this->cfg['config']['settings']['rescale']))
			{
				$jsImg = 0;
				echo '
				<script language="JavaScript" type="text/javascript"><!-- // --><![CDATA[
					var MsgImages'.$this->cfg['id'].' = new Array()';

				foreach($this->posts as $pid => $value)
				{
					if(empty($context['pmx']['settings']['disableHS']) && empty($this->cfg['config']['settings']['disableHS']))
						$this->posts[$pid]['hsbody'] = $this->posts[$pid]['body'];

					if(preg_match_all('~<img[^>]*>~iS', $this->posts[$pid]['body'], $matches) > 0)
					{
						foreach($matches[0] as $data)
						{
							preg_match('~src?=?"([^\"]*\")~i', $data, $src);
							if(isset($src[1]) && strpos($src[1], $modSettings['smileys_url']) === false)
							{
								if(empty($context['pmx']['settings']['disableHS']) && empty($this->cfg['config']['settings']['disableHS']))
								{
									$tmp = str_replace($src[0], ' name="pmx'. $this->cfg['id'] .'img'. $jsImg .'" title="'. substr(strrchr($src[1], '/'), 1) .' '. $src[0], $data);
									$this->posts[$pid]['hsbody'] = substr_replace($this->posts[$pid]['hsbody'],
										'<a href="'. $src[1].' class="highslide" title="'. $txt['pmx_hs_expand'] .'" onclick="return hs.expand(this, {align: \'center\', captionEval: \'this.thumb.title\'})">' .$tmp .'</a>',
										strpos($this->posts[$pid]['hsbody'], $data), strlen($data));
								}
								$tmp = str_replace($src[0], ' name="pmx'. $this->cfg['id'] .'img'. $jsImg .'" '. $src[0], $data);
								$this->posts[$pid]['body'] = substr_replace($this->posts[$pid]['body'], $tmp, strpos($this->posts[$pid]['body'], $data), strlen($data));

								echo '
					MsgImages'.$this->cfg['id'].'['. $jsImg .'] = "pmx'. $this->cfg['id'] .'img'. $jsImg .'";';
								$jsImg++;
							}
						}
					}
				}
				echo '
				// ]]></script>';
			}

			$is_Split = $this->cfg['config']['settings']['split'];
			$is_last = (!empty($this->pageindex) ? ($this->startpage + $this->postspage > count($this->posts) ? count($this->posts) - $this->startpage : $this->postspage) : count($this->posts));

			if($is_Split)
				$half = ceil($is_last / 2);
			else
				$half = $is_last;

			// put the data on the content
			if(!empty($this->cfg['customclass']))
				$isCustFrame = !empty($this->cfg['customclass']['postframe']);
			else
				$isCustFrame = false;
			$spanclass = $isCustFrame && !empty($this->cfg['config']['visuals']['postbody']) ? $this->cfg['config']['visuals']['postbody'] .' ' : '';

			if(!empty($this->pageindex))
				echo '
				<a name="top'. $this->cfg['uniID'] .'"></a>';

			if(!empty($this->pageindex) && !empty($this->cfg['config']['settings']['pgidxtop']))
				echo '
				<div class="smalltext pmx_pgidx_top">'. $txt['pages']. ': '. $this->pageindex . (!empty($modSettings['topbottomEnable']) ? $context['menu_separator'] . ' &nbsp;&nbsp;<a href="#bot'. $this->cfg['uniID'] .'"><strong>' . $txt['go_down'] . '</strong></a>' : '') .'</div>';

			echo '
				<table width="100%" cellpadding="0" cellspacing="0" border="0" style="table-layout:fixed;">
					<tr>
						<td'.($is_Split ? ' style="padding-'.$R_L.':'. ceil($context['pmx']['settings']['panelpad'] / 2) .'px; width:50%;"' : '').' valign="top">';

			reset($this->posts);
			for($i = 0; $i < $this->startpage; $i++)
				each($this->posts);

			while(!empty($is_last))
			{
				list($pid, $post) = each($this->posts);
				if($is_Split && empty($half))
				{
					echo '
						</td>
						<td style="padding-'.$L_R.':'. ceil($context['pmx']['settings']['panelpad'] / 2) .'px; width:50%;" valign="top">';

					reset($this->posts);
					for($i = -1; $i < $this->startpage; $i++)
						each($this->posts);
					list($pid, $post) = each($this->posts);
				}
				$half--;
				$is_last--;

				if(empty($half) && !empty($this->pageindex))
					echo '
							<a name="bot'. $this->cfg['uniID'] .'"></a>';

				echo '
							<div class="'. str_replace('bg', '_bar', $this->cfg['config']['visuals']['postheader']) .' catbg_grid">
								<h4 id="pmx'.$this->cfg['id'].'hspos'. $pid .'" class="'. $this->cfg['config']['visuals']['postheader'] .' catbg_grid">
									'. $post['icon'] .'<span class="normaltext cat_msg_title"><a href="'. $post['href'] .'">'. $post['subject'] .'</a></span>
								</h4>
							</div>
							<div'.(empty($half) || empty($is_last) ? '' :' style="margin-bottom:'. $context['pmx']['settings']['panelpad'] .'px;"') .'>';

				$postbody = trim($this->cfg['config']['visuals']['postbody'] .' '. $this->cfg['config']['visuals']['postframe']);
				if(!empty($postbody))
					echo '
							<div class="'. $postbody .'" style="padding:0 5px;">';

				if(!empty($this->cfg['config']['settings']['equal']) && !empty($this->cfg['config']['settings']['split']))
					echo '
							<div class="pmx_equalheight_'. $this->cfg['id'] .'">';

				echo '
							<div class="smalltext" style="float:'.$L_R.';">
								'. $txt['pmx_text_postby'] . $post['poster']['link'] .', '. $post['time'] . (empty($this->isRead[$post['topic']]) ? '
								<span style="padding-'.$L_R.':5px;">
									<a href="'. $scripturl . '?topic='. $post['topic'] . '.msg' . $post['new_from'] .';topicseen#new" /><img src="' . $settings['lang_images_url'] . '/new.gif" alt="' . $txt['new'] . '" border="0" /></a>
								</span>' : '') .'
							</div>
							<div class="smalltext" style="float:'.$R_L.';">
								'. $txt['pmx_text_replies'] . $post['replies'] .'
							</div>
							<br style="clear:both;" />
							<div class="smalltext msg_bot_pad" style="float:'.$L_R.';">
								'. $txt['pmx_text_board'] . $post['board']['link'] .'
							</div>
							<div class="smalltext msg_bot_pad" style="float:'.$R_L.';">
								'. $txt['pmx_text_views'] . $post['views'] .'
							</div>
							<hr style="clear:both;" />';

				if(empty($context['pmx']['settings']['disableHS']) && empty($this->cfg['config']['settings']['disableHS']))
					echo '
							<div class="pmxhs_imglink" onmouseover="this.className = \'contentover\'" onmouseout="this.className =\'contentout\'" title="'. $txt['pmx_hs_read'] .'" onclick="return hs.htmlExpand(this,
									{ maincontentId: \'np_contid'. $pid .'\', align: \'center\', wrapperClassName: \'highslide-wrapper-html\' })">';
				else
					echo '
							<div class="pmxhs_imglink">';

				if(!empty($this->cfg['config']['settings']['teaser']))
					echo PortaMx_Tease_posts($post['body'], $this->cfg['config']['settings']['teaser'], '', false, empty($this->cfg['config']['settings']['rescale']));
				else
					echo PortaMx_revoveLinks($post['body'], false, empty($this->cfg['config']['settings']['rescale']));

				// post has attach?
				$msgattach = '';
				if(isset($this->attaches[$pid]))
				{
					$msgattach = '
								<div class="pmxhs_posting" style="text-align:'.$L_R.';">';
					echo $msgattach;

					foreach($this->attaches[$pid] as $att)
					{
						if($att['thumb'] != $att['image'])
						{
							$msgattach .= '
									<a href="'. $scripturl .'?action=dlattach;topic='. $post['topic'] .'.0;attach='. $att['image'] .';image"  class="highslide" title="'. $txt['pmx_hs_expand'] .'" onclick="return hs.expand(this, {align: \'center\', captionEval: \'this.thumb.title\'})">
										<img align="top" class="pmxhs_postattach" src="'. $scripturl .'?action=dlattach;topic='. $post['topic'] .'.0;attach='. $att['thumb'] .';image" alt="" title="'. $att['fname'] .'" />
									</a>';

							echo '
									<img align="top" class="pmxhs_postattach" src="'. $scripturl .'?action=dlattach;topic='. $post['topic'] .'.0;attach='. $att['thumb'] .';image" alt="'. $att['fname'] .'" title="" />';
						}
						else
						{
							$msgattach .= '
									<img align="top" class="pmxhs_postattach" src="'. $scripturl .'?action=dlattach;topic='. $post['topic'] .'.0;attach='. $att['thumb'] .';image" alt="'. $att['fname'] .'" title="" />';
							echo '
									<img align="top" class="pmxhs_postattach" src="'. $scripturl .'?action=dlattach;topic='. $post['topic'] .'.0;attach='. $att['thumb'] .';image" alt="'. $att['fname'] .'" title="" />';
						}
					}

					$msgattach .= '
								</div>';
					echo '
								</div>';
				}

				echo '
							</div>';

				if(!empty($this->cfg['config']['settings']['equal']) && !empty($this->cfg['config']['settings']['split']))
					echo '
							</div>';

				echo '
							<a class="smalltext" href="'. $post['href'] .'">'. $txt['pmx_text_readmore'] .'</a>';

				// highslide code
				if(empty($context['pmx']['settings']['disableHS']) && empty($this->cfg['config']['settings']['disableHS']))
				{
					echo '
							<div class="highslide-maincontent" id="np_contid'. $pid .'">
								<div class="highslide-posthead">
									'. $post['icon'] .'<span class="normaltext cat_msg_title">'. preg_replace('~<[^>]*>~i', '', $post['link']) .'</span>
								</div>
								<div class="smalltext" style="float:'.$L_R.';">
									'. $txt['pmx_text_postby'] . preg_replace('~<[^>]*>~i', '', $post['poster']['link']) .', '. $post['time'] . (empty($this->isRead[$post['topic']]) ? '<span style="padding-'.$L_R.':5px;"><img src="' . $settings['lang_images_url'] . '/new.gif" alt="' . $txt['new'] . '" border="0" /></span>' : '') .'
								</div>
								<div class="smalltext" style="float:'.$R_L.';">
									'. $txt['pmx_text_replies'] . $post['replies'] .'
								</div>
								<br style="clear:both;" />
								<div class="smalltext msg_bot_pad" style="float:'.$L_R.';">
									'. $txt['pmx_text_board'] . preg_replace('~<[^>]*>~i', '', $post['board']['link']) .'
								</div>
								<div class="smalltext msg_bot_pad" style="float:'.$R_L.';">
									'. $txt['pmx_text_views'] . $post['views'] .'
								</div>
								<hr style="clear:both;" />';

					if(empty($this->cfg['config']['settings']['rescale']))
						echo '
								'. PortaMx_revoveLinks($post['body'], true, empty($this->cfg['config']['settings']['rescale'])) . $msgattach;
					elseif(isset($post['hsbody']))
						echo '
								'. PortaMx_revoveLinks($post['hsbody'], true, empty($this->cfg['config']['settings']['rescale'])) . $msgattach;
					echo '
							</div>';
				}

				if(!empty($this->cfg['config']['visuals']['postframe']))
				{
					if($this->cfg['config']['visuals']['postframe'] == 'roundframe' || $isCustFrame)
						echo '
							</div>
							<span class="'. $spanclass . ($isCustFrame ? $this->cfg['config']['visuals']['postframe'] .'_bot' : 'lowerframe') .'"><span></span></span>';
					else
						echo '
							</div>
							<span class="'. (!empty($this->cfg['config']['visuals']['postbody']) ? $this->cfg['config']['visuals']['postbody'] .' ' : '') .'botslice"><span></span></span>';
				}
				elseif(!empty($postbody))
					echo '
							</div>';

				echo '
							</div>';

				if($is_Split)
					next($this->posts);
			}

			if($is_Split && $half == 0 && count($this->posts) % 2 != 0)
				echo '
						</td>
						<td style="padding-'.$L_R.':'. ceil($context['pmx']['settings']['panelpad'] / 2) .'px; width:50%;" valign="top">';

			echo '
						</td>
					</tr>
				</table>';

			if(!empty($this->pageindex))
				echo '
				<div class="smalltext pmx_pgidx_bot">'. $txt['pages']. ': '. $this->pageindex . (!empty($modSettings['topbottomEnable']) ? $context['menu_separator'] . ' &nbsp;&nbsp;<a href="#top'. $this->cfg['uniID'] .'"><strong>' . $txt['go_up'] . '</strong></a>' : '') .'</div>';

			if(!empty($this->cfg['config']['settings']['rescale']))
				echo '
				<script language="JavaScript" type="text/javascript"><!-- // --><![CDATA[
					MsgImages'.$this->cfg['id'].'['. $jsImg .'] = window.setInterval("ResizeImages(\''.$this->cfg['id'].'\', '. $this->cfg['config']['settings']['rescale'] .')", 20);
				// ]]></script>';
		}
	}
}
?>